import { defineComponent, ref } from 'vue'
import type { Shop } from '@/types/model'
import ShopInfo from '@/components/ShopInfo'
import { useRouter } from 'vue-router'
import { hotListApi } from '@/api/shop'

const useNearbyListEffect = () => {
  const shopsRef = ref<Shop[]>([])

  const getNearbyList = async () => {
    const res = await hotListApi()
    if (res.code === 0) {
      shopsRef.value = res.data
    }
  }

  return {
    shopsRef,
    getNearbyList
  }
}

export default defineComponent({
  name: 'NearBy',
  setup () {
    const router = useRouter()
    const { shopsRef, getNearbyList } = useNearbyListEffect()
    const handleInfoClick = (shop: Shop) => {
      router.push(`/shop/${shop.id}`)
    }

    getNearbyList()
    return () => {
      const shopList = shopsRef.value.map(shop => (
        <ShopInfo shop={ shop } onClick={ () => handleInfoClick(shop) } />
      ))
      return (
        <div class="nearby">
          <h3 class="nearby__title">附近店铺</h3>
          { shopList }
        </div>
      )
    }
  }
})
